//
//  AesSecureHelper.swift
//  cangchu
//
//  Created by kang on 2022/1/25.
//

import Foundation
import CryptoSwift

public class AesSecureHelper:SecureProtocol{
    
    private var key:String?
    private var algorithm = AlgorithmEnum.AES
    
    public init(_ key:String){
        self.key = key
    }
    
    public override func encrypt(param: String) -> String {
        return Endcode_AES_ECB(strToEncode: param)
    }
    
    
    public override func deEncrypt(param: String) -> String {
        return Decode_AES_ECB(strToDecode: param)
    }
    
    public override func getAlgorithm() -> AlgorithmEnum {
        return algorithm
    }
    
    public override func getKey() -> String {
        return self.key!
    }
    
    //加密
    private func Endcode_AES_ECB(strToEncode:String)->String {
            // 从String 转成data
            let data = strToEncode.data(using: String.Encoding.utf8)
            
            // byte 数组
            var encrypted: [UInt8] = []
            do {
                encrypted = try AES(key: key!.bytes, blockMode: ECB()).encrypt(data!.bytes)
            } catch {
            }
            
            let encoded =  Data(encrypted)
            //加密结果要用Base64转码
            return encoded.base64EncodedString()
        }
    
    //解密
    private func Decode_AES_ECB(strToDecode:String)->String {
        //decode base64
        let data = NSData(base64Encoded: strToDecode, options: NSData.Base64DecodingOptions.init(rawValue: 0))
        
        // byte 数组
        var encrypted: [UInt8] = []
        let count = data?.length
        
        // 把data 转成byte数组
        for i in 0..<count! {
            var temp:UInt8 = 0
            data?.getBytes(&temp, range: NSRange(location: i,length:1 ))
            encrypted.append(temp)
        }
        
        // decode AES
        var decrypted: [UInt8] = []
        do {
            decrypted = try AES(key: key!.bytes, blockMode: ECB()).decrypt(encrypted)
        } catch {
        }
        
        // byte 转换成NSData
        let encoded = Data(decrypted)
        var str = ""
        //解密结果从data转成string
        str = String(bytes: encoded.bytes, encoding: .utf8)!
        return str
    }
}
